from pydantic import BaseModel
import json,os

Settings_File='clock.json'

class ClockSettingsDto(BaseModel):
    bellRepeatTime:int
    checkPeriod:int
    enableBellRing:bool
    enableTimeReport:bool
    reportMinutes:str
    reportTemplate:str
    silentHours:str

class ClockSettings:
    def __init__(self,settings=None) -> None:
        if not settings:
            settings={}
        self.bellRepeatTime:int=settings.get('bellRepeatTime',1)
        self.checkPeriod:int=settings.get('checkPeriod',30)
        self.enableBellRing:bool=settings.get('enableBellRing',True)
        self.enableTimeReport:bool=settings.get('enableTimeReport',True)
        self.reportMinutes:list[int]=settings.get('reportMinutes',[0,30])
        self.reportTemplate:str=settings.get('reportTemplate',"现在是{hour}点{minute}分")
        self.silentHours:list[int]=settings.get('silentHours',[0, 1, 2, 3, 4, 5, 6, 12, 13, 23])
    
    @classmethod
    def load_from_dto(cls,dto:ClockSettingsDto):
        settings=dto.dict()
        reportMinutes=dto.reportMinutes
        settings['reportMinutes']=sorted(list(map(int,reportMinutes.split())))
        settings['silentHours']=sorted(list(map(int,dto.silentHours.split())))
        return cls(settings)
    
    def to_dto(self):
        settings=self.__dict__
        settings['reportMinutes']=' '.join(map(str,self.reportMinutes))
        settings['silentHours']=' '.join(map(str,self.silentHours))
        return ClockSettingsDto(**settings)

    @classmethod
    def load_from_file(cls):
        if not os.path.exists(Settings_File):
            return ClockSettings()
        with open(Settings_File,'r',encoding='utf8') as f:
            settings=json.load(f)
        return cls(settings)

    def save_to_file(self):
        with open(Settings_File,'w',encoding='utf8') as f:
            json.dump(self.__dict__,f)
        
    

if __name__ == '__main__':
    # print(ClockSettings().save_to_file())
    clock=ClockSettings.load_from_file()
    dto=clock.to_dto()
    pass